package com.copasso.cocobill.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bumptech.glide.Glide;
import com.copasso.cocobill.R;
import com.copasso.cocobill.common.Constants;
import com.copasso.cocobill.model.bean.local.BSort;
import com.copasso.cocobill.model.bean.local.NoteBean;
import com.copasso.cocobill.model.repository.LocalRepository;
import com.copasso.cocobill.ui.adapter.MainFragmentPagerAdapter;
import com.copasso.cocobill.base.BaseActivity;
import com.copasso.cocobill.ui.fragment.MonthChartFragment;
import com.copasso.cocobill.ui.fragment.MonthListFragment;
import com.copasso.cocobill.utils.DateUtils;
import com.copasso.cocobill.utils.GlideCacheUtil;
import com.copasso.cocobill.utils.SharedPUtils;
import com.copasso.cocobill.utils.SnackbarUtils;
import com.copasso.cocobill.utils.ThemeManager;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;
import android.net.Uri;
import android.provider.MediaStore;
import android.graphics.Bitmap;
import com.yalantis.ucrop.UCrop; // For UCrop
import java.io.File; // For File
import java.io.IOException; // For IOException
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable; // For BitmapDrawable
import android.graphics.drawable.Drawable; // For Drawable
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.google.android.material.appbar.AppBarLayout; // For AppBarLayout
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.text.InputType;
/**
 * 主界面activity
 */
public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {
    private TextToSpeech textToSpeech;
    private boolean isTextToSpeechInitialized = false;
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private DrawerLayout drawer;
    private NavigationView navigationView;
    private TextView tOutcome;
    private TextView tIncome;
    private TextView tTotal;

    private View drawerHeader;
    private ImageView drawerIv;
    private TextView drawerTvAccount, drawerTvMail;

    protected static final int USERINFOACTIVITY_CODE = 0;
    protected static final int LOGINACTIVITY_CODE = 1;
    protected static final int REQUEST_IMAGE_PICK = 2;
    protected static final int REQUEST_IMAGE_CROP = 3;
    private static final String PREF_BACKGROUND_URI = "background_uri";
    // Tab
    private FragmentManager mFragmentManager;
    private MainFragmentPagerAdapter mFragmentPagerAdapter;
    private MonthListFragment monthListFragment;
    private MonthChartFragment monthChartFragment;

    private String currentUser;
    private Uri resultUri;
    /***************************************************************************/
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        // 初始化 TextToSpeech
        textToSpeech = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                int result = textToSpeech.setLanguage(Locale.SIMPLIFIED_CHINESE);
                isTextToSpeechInitialized = (result != TextToSpeech.LANG_MISSING_DATA && result != TextToSpeech.LANG_NOT_SUPPORTED);
                if (!isTextToSpeechInitialized) {
                    Toast.makeText(MainActivity.this, "不支持中文语音播报", Toast.LENGTH_SHORT).show();
                }
                String hello ="Hello";
                textToSpeech.speak(hello, TextToSpeech.QUEUE_FLUSH,null,null);
            } else {
                Toast.makeText(MainActivity.this, "TextToSpeech 初始化失败", Toast.LENGTH_SHORT).show();
            }
        });
        // 第一次进入将默认账单分类添加到数据库
        if (SharedPUtils.isFirstStart(mContext)) {
            Log.i(TAG, "第一次进入将默认账单分类添加到数据库");
            NoteBean note = new Gson().fromJson(Constants.BILL_NOTE, NoteBean.class);
            List<BSort> sorts = note.getOutSortlis();
            sorts.addAll(note.getInSortlis());
            LocalRepository.getInstance().saveBsorts(sorts);
            LocalRepository.getInstance().saveBPays(note.getPayinfo());
        }

        monthListFragment = new MonthListFragment();
        monthChartFragment = new MonthChartFragment();
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        toolbar = findViewById(R.id.toolbar);
        tabLayout = findViewById(R.id.tablayout);
        viewPager = findViewById(R.id.main_viewpager);
        drawer = findViewById(R.id.main_drawer);
        navigationView = findViewById(R.id.main_nav_view);
        tOutcome = findViewById(R.id.t_outcome);
        tIncome = findViewById(R.id.t_income);
        tTotal = findViewById(R.id.t_total);

        // 初始化Toolbar
        toolbar.setTitle("猪猪记账本");
        setSupportActionBar(toolbar);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        drawerHeader = navigationView.inflateHeaderView(R.layout.drawer_header);
        drawerIv = drawerHeader.findViewById(R.id.drawer_iv);
        drawerTvAccount = drawerHeader.findViewById(R.id.drawer_tv_name);
        drawerTvMail = drawerHeader.findViewById(R.id.drawer_tv_mail);

        // 设置头部账户
        setDrawerHeaderAccount();

        // 初始化ViewPager
        mFragmentManager = getSupportFragmentManager();
        mFragmentPagerAdapter = new MainFragmentPagerAdapter(mFragmentManager);
        mFragmentPagerAdapter.addFragment(monthListFragment, "明细");
        mFragmentPagerAdapter.addFragment(monthChartFragment, "图表");

        monthListFragment.setMonthListListener((outcome, income, total) -> {
            Log.e("total", "total" + total);
            if (Float.parseFloat(total) < 0) {
                tTotal.setTextColor(Color.RED);
                Toast.makeText(MainActivity.this,"当前结余为负数，请注意收支平衡",Toast.LENGTH_SHORT).show();

                // 添加语音播报
                String message = "当前结余为负数，请注意收支平衡";
                textToSpeech.speak(message, TextToSpeech.QUEUE_FLUSH, null, "1");
            }
            else{
                tTotal.setTextColor(getResources().getColor(R.color.textWhite));
            }
            // 检查收入是否大于100000
            if (Float.parseFloat(income) > 100000) {
                String praiseMessage = "棒棒哒！";
                textToSpeech.speak(praiseMessage, TextToSpeech.QUEUE_FLUSH, null, "2");
            }


            tOutcome.setText(outcome);
            tIncome.setText(income);
            tTotal.setText(total);
        });

        viewPager.setAdapter(mFragmentPagerAdapter);

        // 初始化TabLayout
        tabLayout.addTab(tabLayout.newTab().setText("明细"));
        tabLayout.addTab(tabLayout.newTab().setText("图表"));
        tabLayout.setupWithViewPager(viewPager);
        // 恢复背景
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String uriString = prefs.getString(PREF_BACKGROUND_URI, null);
        int savedBlurRadius = prefs.getInt("blur_radius", 10); // 默认模糊半径为10
        if (uriString != null) {
            Uri imageUri = Uri.parse(uriString);
            setAppBarBackground(imageUri,savedBlurRadius);
        }
    }

    @Override
    protected void initClick() {
        super.initClick();
        // 监听侧滑菜单项
        navigationView.setNavigationItemSelectedListener(this);
        // 监听侧滑菜单头部点击事件
        drawerHeader.setOnClickListener(v -> {
            if (currentUser.equalsIgnoreCase("")) {
                startActivityForResult(new Intent(mContext, LandActivity.class), LOGINACTIVITY_CODE);
            } else {
                startActivityForResult(new Intent(mContext, UserInfoActivity.class), USERINFOACTIVITY_CODE);
            }
        });
    }

    /***************************************************************************/
    /**
     * 设置toolbar右侧菜单
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main_toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.toolbar_date:
                // 时间选择器
                new TimePickerBuilder(mContext, (Date date, View v) -> {
                    monthListFragment.changeDate(DateUtils.date2Str(date, "yyyy"), DateUtils.date2Str(date, "MM"));
                    monthChartFragment.changeDate(DateUtils.date2Str(date, "yyyy"), DateUtils.date2Str(date, "MM"));
                }).setType(new boolean[] { true, true, false, false, false, false })
                        .setRangDate(null, Calendar.getInstance())
                        .isDialog(true)// 是否显示为对话框样式
                        .build().show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 监听左滑菜单
     *
     * @param item
     * @return
     */
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_sync: // 同步账单
                if (currentUser.equalsIgnoreCase(""))
                    SnackbarUtils.show(mContext, "请先登陆");
                break;
            case R.id.nav_setting:
                startActivity(new Intent(mContext, SettingActivity.class));
                break;
            case R.id.nav_about:
                startActivity(new Intent(mContext, AboutActivity.class));
                break;
            case R.id.nav_theme:
                showUpdateThemeDialog();
                break;
            case R.id.nav_background:
                showImagePickerDialog();
                break;
            case R.id.nav_exit:
                exitUser();
                break;
            default:
                break;
        }

        drawer.closeDrawer(GravityCompat.START);

        return true;
    }

    /**
     * 显示修改主题色 Dialog
     */
    private void showUpdateThemeDialog() {
        String[] themes = ThemeManager.getInstance().getThemes();
        new MaterialDialog.Builder(mContext)
                .title("选择主题")
                .titleGravity(GravityEnum.CENTER)
                .items(themes)
                .negativeText("取消")
                .itemsCallback(((dialog, itemView, position, text) -> {
                    ThemeManager.getInstance().setTheme(mActivity, themes[position]);
                }))
                .show();
    }

    /**
     * 显示选择图片的对话框
     */
    private void showImagePickerDialog() {
        new MaterialDialog.Builder(mContext)
                .title("选择操作")
                .titleGravity(GravityEnum.CENTER)
                .items(new String[] { "选择图片", "取消" })
                .itemsCallback((dialog, itemView, position, text) -> {
                    if (position == 0) {
                        // 选择图片
                        pickImageFromGallery();
                    } else {
                        // 取消
                        dialog.dismiss();
                    }
                })
                .show();
    }

    private void pickImageFromGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
    }

    /**
     * 退出登陆 Dialog
     */
    private void exitUser() {
        new MaterialDialog.Builder(mContext)
                .title("确认退出")
                .content("退出后将清空所有数据")
                .positiveText("确定")
                .onPositive((dialog, which) -> {
                    GlideCacheUtil.getInstance().clearImageDiskCache(mContext);
                    // 清除本地数据
                    LocalRepository.getInstance().deleteAllBills();
                    // 重启
                    finish();
                    Intent intent = getIntent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                })
                .negativeText("取消")
                .show();
    }

    /**
     * 监听Activity返回值
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case USERINFOACTIVITY_CODE:
                case LOGINACTIVITY_CODE:
                    setDrawerHeaderAccount();
                    break;
                case REQUEST_IMAGE_PICK:
                    if (data != null) {
                        Uri selectedImageUri = data.getData();
                        if (selectedImageUri != null) {
                            // 启动 uCrop 裁剪活动
                            startCrop(selectedImageUri);
                        } else {
                            Toast.makeText(this, "无法获取图片", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case UCrop.REQUEST_CROP:
                    resultUri = UCrop.getOutput(data);
                    if (resultUri != null) {
                        showBlurRadiusDialog(resultUri);
                    }
                    break;
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            final Throwable cropError = UCrop.getError(data);
            if (cropError != null) {
                Toast.makeText(this, cropError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void startCrop(Uri sourceUri) {
        // 获取屏幕宽度
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        // 将 179dp 转换为像素
        int appBarHeight = (int) (75 * getResources().getDisplayMetrics().density);

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), "cropped_image.jpg"));
        UCrop.of(sourceUri, destinationUri)
                .withAspectRatio(screenWidth, appBarHeight) // 设置裁剪比例
                .withMaxResultSize(screenWidth, appBarHeight) // 设置最大结果尺寸
                .start(this);
    }

    /*
    private void setAppBarBackground(Uri imageUri) {
           AppBarLayout appBarLayout = findViewById(R.id.app_bar_layout);
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
            Drawable drawable = new BitmapDrawable(getResources(), bitmap);
            appBarLayout.setBackgroundResource(R.drawable.icon_banner_point1);
            appBarLayout.setBackground(drawable);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    private void setAppBarBackground(Uri imageUri,int blurRadius) {
        if (imageUri == null) {
            Log.e("MainActivity", "Image URI is null, cannot set background.");
            return;
        }
        LinearLayout linearLayout = findViewById(R.id.linear_Layout);
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
            Bitmap blurredBitmap = blurBitmap(bitmap, blurRadius);
            Drawable drawable = new BitmapDrawable(getResources(), blurredBitmap);
            linearLayout.setBackground(drawable);

            // Save the URI to SharedPreferences
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            prefs.edit()
                    .putString(PREF_BACKGROUND_URI, imageUri.toString())
                    .putInt("blur_radius", blurRadius)
                    .apply();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
    private void setAppBarBackground(Uri imageUri) {
        TabLayout tabLayout = findViewById(R.id.tablayout); // Change to TabLayout if that's the correct type
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
            Drawable drawable = new BitmapDrawable(getResources(), bitmap);
            tabLayout.setBackgroundResource(R.drawable.icon_banner_point1); // Assuming you want to set background on TabLayout
            tabLayout.setBackground(drawable);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    private void showBlurRadiusDialog(Uri imageUri) {
        new MaterialDialog.Builder(mContext)
                .title("设置模糊半径")
                .titleGravity(GravityEnum.CENTER)
                .inputType(InputType.TYPE_CLASS_NUMBER)
                .input("输入0到25之间的数字", "", (dialog, input) -> {
                    try {
                        int radius = Integer.parseInt(input.toString());
                        if (radius < 0 || radius > 25) {
                            Toast.makeText(mContext, "模糊半径必须在0到25之间", Toast.LENGTH_SHORT).show();
                        } else {
                            setAppBarBackground(imageUri, radius);
                        }
                    } catch (NumberFormatException e) {
                        Toast.makeText(mContext, "请输入有效的数字", Toast.LENGTH_SHORT).show();
                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .onNegative((dialog, which) -> dialog.dismiss())
                .show();
    }

    private Bitmap blurBitmap(Bitmap bitmap, int radius) {
        Bitmap outputBitmap = Bitmap.createBitmap(bitmap);
        RenderScript rs = RenderScript.create(this);
        Allocation input = Allocation.createFromBitmap(rs, bitmap);
        Allocation output = Allocation.createFromBitmap(rs, outputBitmap);
        ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setRadius(radius); // Use the user-defined blur radius
        script.setInput(input);
        script.forEach(output);
        output.copyTo(outputBitmap);
        rs.destroy();
        return outputBitmap;
    }
    /**
     * 设置DrawerHeader的用户信息
     */
    public void setDrawerHeaderAccount() {
        currentUser = SharedPUtils.getName(MainActivity.this);
        // 获取当前用户
        if (!currentUser.equalsIgnoreCase("")) {
            drawerTvAccount.setText(currentUser);
        } else {
            drawerTvAccount.setText("账号");
            drawerTvMail.setText("点我登陆");
            drawerIv.setImageResource(R.mipmap.ic_def_icon);
        }
    }
}